//TCPTest.java
package com.ylaihui.net;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTest {
    @Test
    public void serverTest() throws IOException {
        ServerSocket ss = new ServerSocket(65500);

        System.out.println("accepting...");
        Socket accept = ss.accept();

        InputStream is = accept.getInputStream();

        // 如果客户端发出的消息有汉字，这里不适合使用 byte[]
        byte[] chars = new byte[10];
        int len = 0;
        while ((len = is.read(chars)) != -1) {
            String string = new String(chars, 0, len);
            System.out.print(string);
        }
        is.close();
        accept.close();
        ss.close();
    }

    @Test
    public void clientTest() throws IOException {
        InetAddress localhost = InetAddress.getByName("localhost");
        Socket socket = new Socket(localhost, 65500);

        OutputStream os = socket.getOutputStream();
        os.write("this is client".getBytes());

        os.close();
        socket.close();
    }
}
